package face.pay.web.paycode.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import face.pay.config.CodePayConfig;
import face.pay.dao.MchPayCodeBatchDao;
import face.pay.dao.MchPayCodeDao;
import face.pay.entity.MchPayCodeBatch;
import face.pay.entity.MchPayCode;
import face.pay.entity.UserInfo;
import face.pay.util.DateUtil;
import face.pay.util.MatrixToImageWriter;
import face.pay.util.ResultMessage;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import face.pay.web.paycode.service.IPayCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@Slf4j
public class PayCodeServiceImpl implements IPayCodeService {

    private static final int BUFFER_SIZE = 2 * 1024;
    @Autowired
    private MchPayCodeDao mchPayCodeDao;

    @Autowired
    private MchPayCodeBatchDao payCodeBatchDao;

    @Autowired
    CodePayConfig codePayConfig;

    @Override
    public PageData<MchPayCodeBatch> queryBatchCode(PageParam pageParam, UserInfo loginUser,MchPayCodeBatch mchPayCodeBatch){

        PageHelper.startPage(pageParam.getPageNo(),pageParam.getPageSize());

        mchPayCodeBatch.setOemId(loginUser.getOemId());

        List<MchPayCodeBatch> mchPayCodeBatchs = this.payCodeBatchDao.queryList(mchPayCodeBatch);

        PageInfo<MchPayCodeBatch> pageInfo = new PageInfo <>(mchPayCodeBatchs);

        PageData<MchPayCodeBatch> pageData = new PageData<>(pageInfo.getTotal(),mchPayCodeBatchs);

        return pageData;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addBatchCode(UserInfo loginUser, MchPayCodeBatch mchPayCodeBatch) {

        log.info("批量创建收款二维码");
        Integer oemId = loginUser.getOemId();

        mchPayCodeBatch.setOemId(oemId);
        Integer batchCount = mchPayCodeBatch.getBatchCount();
        log.info("batchCount："+batchCount);

        this.payCodeBatchDao.insert(mchPayCodeBatch);

        Integer batchId = mchPayCodeBatch.getId();

        List<MchPayCode> list =  new ArrayList<>();

        for(Integer i=0;i<batchCount;i++){
            MchPayCode mchPayCode =  new MchPayCode();
            mchPayCode.setOemId(oemId);
            mchPayCode.setBatchId(batchId);
            String code = UUID.randomUUID().toString();
            String url = codePayConfig.getPayUrl()+"?code="+code;
            mchPayCode.setUrl(url);
            mchPayCode.setCode(code);
            mchPayCode.setCreatedBy(loginUser.getId());
            list.add(mchPayCode);
        }

        this.mchPayCodeDao.insertBatch(list);


        return ResultMessage.createSuccess();

    }

    @Override
    public void down(UserInfo loginUser, Integer batchId, HttpServletRequest request, HttpServletResponse response) {

        try {
            log.info("二维码批次："+batchId);

            List<MchPayCode> list = this.mchPayCodeDao.queryListByBatchId(batchId);

            String tmpDir = codePayConfig.getTmpDir();


            String batchFile = tmpDir+File.separator+batchId+"_"+ DateUtil.getSecondTimestamp(new Date());

            File file  = new File(batchFile);
            if(file.exists()){

            }else {
                file.mkdir();
            }

            List<File> files = new ArrayList<>();

            for(MchPayCode mchPayCode:list){

                String code=mchPayCode.getCode();
                Integer id  =  mchPayCode.getId();

                String text =mchPayCode.getUrl();
                //codePayConfig.getPayUrl()+"?code="+code;

                log.info("二维码内容："+text);
                int width = 300; // 二维码图片宽度
                int height = 300; // 二维码图片高度
                String format = "jpg";// 二维码的图片格式

                Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

                BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
                        BarcodeFormat.QR_CODE, width, height, hints);
                // 生成二维码
                String fileName=batchFile+File.separator+String.valueOf(id)+".jpg";
                File outputFile = new File(fileName);
                MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
                files.add(outputFile);
            }

            String zipName = batchFile+File.separator+"code.zip";

            log.info("压缩路径："+zipName);
            File zipFile  =  new File(zipName);
            zipFile.createNewFile();
            log.info("zipName"+zipName);

            FileOutputStream outputStream =  new FileOutputStream(zipName);

            toZip(files,outputStream);

            outputStream.close();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            InputStream fis = new BufferedInputStream(new FileInputStream(zipName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            String aName = new String(String.valueOf(batchId))+"_code.zip";

            //
            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(aName.getBytes("GB2312"), "ISO8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }



    public static void toZip(List<File> srcFiles, OutputStream out  ) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            log.info("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            log.info("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }

            }

        }
    }

}
